package com.ruyuan.eshop.common.service.aftersale.impl;

import cn.hutool.json.JSONUtil;
import com.ruyuan.eshop.common.client.trade.AfterSaleClient;
import com.ruyuan.eshop.common.model.aftersale.dos.AfterSaleGoodsDO;
import com.ruyuan.eshop.common.model.aftersale.dos.AfterSaleServiceDO;
import com.ruyuan.eshop.common.model.aftersale.dto.PutInWarehouseDTO;
import com.ruyuan.eshop.common.model.aftersale.enums.ServiceStatusEnum;
import com.ruyuan.eshop.common.model.aftersale.vo.ApplyAfterSaleVO;
import com.ruyuan.eshop.common.service.aftersale.AfterSaleManager;
import com.ruyuan.eshop.common.service.aftersale.AfterSaleQueryManager;
import com.ruyuan.eshop.common.service.aftersale.AfterSaleRefundManager;
import com.ruyuan.eshop.common.service.aftersale.PaySuccessCancelOrderRefundManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 支付成功 取消订单的自动退款处理器
 * @author pwd
 * @version 1.0
 **/
@Service
public class PaySuccessCancelOrderRefundManagerImpl implements PaySuccessCancelOrderRefundManager {

    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(PaySuccessCancelOrderRefundManagerImpl.class);

    @Autowired
    private AfterSaleQueryManager afterSaleQueryManager;

    @Autowired
    private AfterSaleManager afterSaleManager;

    @Autowired
    private AfterSaleRefundManager afterSaleRefundManager;

    @Autowired
    private AfterSaleClient afterSaleClient;

    /**
     * 取消订单后，自动审核自动退款逻辑
     *
     * @param afterSaleServiceDO 售后工单
     * @return 处理结果
     */
    @Override
    @Transactional(value = "tradeTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean process(AfterSaleServiceDO afterSaleServiceDO) {

        ApplyAfterSaleVO detail = afterSaleQueryManager.getApplyAfterSale(afterSaleServiceDO.getSn());
        LOG.info("售后工单详情为 [{}]", JSONUtil.toJsonPrettyStr(detail));
        this.afterSaleManager.auditForAuto(
                afterSaleServiceDO.getSn(),
                ServiceStatusEnum.PASS.value(),
                detail.getRefundInfo().getRefundPrice(),
                detail.getReturnAddr(),
                "定时任务自动审核操作");

        LOG.info("审核工单完成 审核的工单sn为 [{}]", afterSaleServiceDO.getSn());

        List<PutInWarehouseDTO> putInWarehouseDTOList = new ArrayList<>();

        buildPutInWarehouseDTOList(detail.getGoodsList(), putInWarehouseDTOList);

        LOG.info("构造好的商品入库列表为 [{}]", JSONUtil.toJsonPrettyStr(putInWarehouseDTOList));

        this.afterSaleManager.putInWarehouseForAuto(afterSaleServiceDO.getSn(), putInWarehouseDTOList, "自动审核的商品入库操作");
        LOG.info("自动退款 商品入库的逻辑完成 ");

        this.afterSaleRefundManager.sellerRefundForAuto(afterSaleServiceDO.getSn());

        LOG.info("完成退款 售后sn码为 [{}]", afterSaleServiceDO.getSn());

        try {
            this.afterSaleClient.refundCompletion();
        } catch (Exception e) {
            LOG.error("发生异常", e);
        }
        LOG.info("将订单改为退款完成的状态");
//        AfterSaleChangeMessage afterSaleChangeMessage = null;
//        try {
//            // 通知云平台 那个订单退款成功了
//            afterSaleChangeMessage = new AfterSaleChangeMessage();
//            afterSaleChangeMessage.setServiceSn(afterSaleServiceDO.getSn());
//            afterSaleChangeMessage.setServiceStatus(com.scholar.manager.api.enums.ServiceStatusEnum.valueOf(com.scholar.manager.api.enums.ServiceStatusEnum.COMPLETED.value()));
//            afterSaleChangeMessage.setServiceType(com.scholar.manager.api.enums.ServiceTypeEnum.ORDER_CANCEL);
//            Boolean result = cloudPlatformNotifyPaySuccessApi.informCloudRefundSuccessEvent(afterSaleChangeMessage);
//            LOG.info("通知云平台 售后工单退款成功了 通知的消息体为 [{}] 通知结果为 [{}]",
//                    JSONUtil.toJsonStr(afterSaleChangeMessage), result);
//        } catch (Exception e) {
//            LOG.error("通知云平台退款成功时，发生异常 消息体为 [{}]", JSONUtil.toJsonStr(afterSaleChangeMessage), e);
//        }

        return true;
    }

    /**
     * 根据售后服务商品列表 构造入库商品列表
     * @param goodsList 商品列表
     * @param putInWarehouseDTOList 入库商品列表
     */
    private void buildPutInWarehouseDTOList(List<AfterSaleGoodsDO> goodsList, List<PutInWarehouseDTO> putInWarehouseDTOList) {
        PutInWarehouseDTO putInWarehouseDTO = null;
        for (AfterSaleGoodsDO afterSaleGoodsDO : goodsList) {
            putInWarehouseDTO = new PutInWarehouseDTO();
            putInWarehouseDTO.setGoodsId(afterSaleGoodsDO.getGoodsId());
            putInWarehouseDTO.setSkuId(afterSaleGoodsDO.getSkuId());
            putInWarehouseDTO.setReturnNum(afterSaleGoodsDO.getReturnNum());
            putInWarehouseDTO.setStorageNum(afterSaleGoodsDO.getReturnNum());
            putInWarehouseDTOList.add(putInWarehouseDTO);
        }
    }

}
